$(function () {
    template.defaults.imports.dataFormat = function (dtStr) {
        const dt = new Date(dtStr)
        const y = dt.getFullYear()
        const m = (dt.getMonth() + 1).toString().padStart(2, '0')
        const d = dt.getDate().toString().padStart(2, '0')

        const hh = dt.getHours().toString().padStart(2, '0')
        const mm = dt.getMinutes().toString().padStart(2, '0')
        const ss = dt.getSeconds().toString().padStart(2, '0')

        return `${y}/${m}/${d} ${hh}:${mm}:${ss}`
    }
    let q = {
        pagenum: 1,
        pagesize: 3,
        cate_id: '',
        state: ''
    }

    function getArtList() {
        $.get('/my/article/list', q, function (res) {
            if (res.status === 0) {
                const htmlStr = template('tmpl', res)
                $('tbody').html(htmlStr)

                renderPage(res.total)
            }
        })
    }

    function initCateList() {
        $.get('/my/article/cates', function (res) {
            if (res.status === 0) {
                const htmlStr1 = template('tmpl-opt', res)
                $('[name="cate_id"]').html(htmlStr1)
                layui.form.render('select')
            }
        })
    }

    initCateList()
    getArtList()

    $('form').on('submit', function (e) {
        e.preventDefault()
        q.cate_id = $('[name="cate_id"]').val()
        q.state = $('[name="state"]').val()

        getArtList()
    })

    $('[type="reset"]').on('click', function () {
        q = {
            pagenum: 1,
            pagesize: 3,
            cate_id: '',
            state: ''
        }

        getArtList()
    })
    function renderPage(total) {
        layui.laypage.render({
            elem: 'page-box',
            count: total,
            limit: q.pagesize,
            curr: q.pagenum,
            limits: [2, 3, 5, 8, 10],
            layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],

            jump: function (obj, first) {
                q.pagenum = obj.curr
                q.pagesize = obj.limit

                if (first !== true) {
                    getArtList()
                }
            }
        })
    }
    $('body').on('click', '.btn_delete', function () {
        const id = $(this).attr('data-id')
        layer.confirm('是否删除此文章？', { icon: 3, title: '提示' }, function (index) {
            $.get('/my/article/delete/' + id, function (res) {
                if (res.status === 0) {
                    if (q.pagenum > 1 && $('tbody tr').length === 1) {
                        q.pagenum--
                    }
                    getArtList()
                }
            })
            layer.close(index)
        })
    })
})